package com.hdcircles.autoform.ui.label.Service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.hdcircles.autoform.model.bean.FormBean;
import com.hdcircles.autoform.presenter.FormServicePresenter;
import com.hdcircles.autoform.presenter.contract.FormServiceContract;
import com.hdcircles.autoform.util.LogUtil;
import com.hdcircles.autoform.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hdcircles on 2016/11/21.
 */

public class FormService extends Service implements FormServiceContract.View {

    private static FormServicePresenter mPresenter;

    private FormBinder mBinder=new FormBinder();

    private List<FormBean> formBeanList;

    public final static String BROADCAST_SERVICE_ACTION="com.hdcircles.autoform.broadcast.SERVICE_ACTION";

    @Override
    public void onCreate() {
        super.onCreate();
        mPresenter=new FormServicePresenter();
        mPresenter.attachView(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }


    @Override
    public boolean onUnbind(Intent intent) {
        mPresenter.detachView();
        return super.onUnbind(intent);
    }

    @Override
    public void showError(String msg) {
//        ToastUtil.shortShow(msg);
    }

    @Override
    public void useNightMode(boolean isNight) {

    }

    @Override
    public void sendBroadcast(List<FormBean> formList) {
        Intent intent=new Intent(BROADCAST_SERVICE_ACTION);
        Bundle bundle=new Bundle();
        bundle.putParcelableArrayList("formList",((ArrayList)formList));
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }

    public static class FormBinder extends Binder{

        boolean isStop;

        public void  startFormService(final String email){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!isStop){
                        mPresenter.getFormData(email);
                        try {
                            Thread.sleep(30000);//30秒访问一次服务器
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }

        public void setStop(boolean stop) {
            isStop = stop;
        }
    }
}
